package com.chen.filter;


import com.chen.service.ILoginService;
import com.chen.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName: DoFIlter1
 * Package: com.chen.filter
 * Description:
 *
 * @Author 陈俊辉
 * @Create 2024/4/12 11:53
 * @Version 1.0
 */
@WebFilter("/**")
@Component
public class DoFIlter1 implements Filter {
    @Resource
    public ILoginService loginService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        HttpServletRequest httpServletRequest=(HttpServletRequest)servletRequest;

        HttpServletResponse httpServletResponse=(HttpServletResponse)servletResponse;
        //1.先判断是不是login
        String url = httpServletRequest.getRequestURL().toString();
        if(url.contains("/login")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        String token = httpServletRequest.getHeader("token");
         //获取token
        Claims claims = JwtUtil.parseJWT(token);
        String username = (String)claims.get("username");
        String password = (String)claims.get("password");
        //登录校验
        loginService.doLogin(username,password);
        //放行
        filterChain.doFilter(servletRequest,servletResponse);

    }


}
